package org.xiaov.lunasql.engine.function;

import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;

/**
 * <p>
 * Substring2Substr
 * </p>
 *
 * @author lzq
 * @since 2024/12/17 19:52
 */
public class Substring2Substr implements MySqlFunction {
    private final static String METHOD_NAME1 = "substring";
    private final static String METHOD_NAME2 = "substr";
    private final static String TARGET_METHOD_NAME = "substr";

    @Override
    public boolean accept(SQLMethodInvokeExpr methodInvokeExpr) {
        return METHOD_NAME1.equalsIgnoreCase(methodInvokeExpr.getMethodName())
                || METHOD_NAME2.equalsIgnoreCase(methodInvokeExpr.getMethodName());
    }

    @Override
    public void transform(SQLMethodInvokeExpr methodInvokeExpr) {
        methodInvokeExpr.setMethodName(TARGET_METHOD_NAME);
        if (methodInvokeExpr.getArguments().size() == 1) {
            // 两种情况
            // SUBSTR(str FROM pos)
            // SUBSTRING(str FROM pos FOR len)
            if (methodInvokeExpr.getFrom() != null) {
                methodInvokeExpr.getArguments().add(methodInvokeExpr.getFrom());
                methodInvokeExpr.setFrom(null);
            }
            if (methodInvokeExpr.getFor() != null) {
                methodInvokeExpr.getArguments().add(methodInvokeExpr.getFor());
                methodInvokeExpr.setFor(null);
            }
        }
    }
}
